<?php
namespace Entities\Financeiro;
use Doctrine\ORM\Query;
use Doctrine\ORM\EntityRepository;

class CategoriaRepository extends EntityRepository
{
	public function listar($params = array())
	{
		$qb		= $this->getEntityManager()->createQueryBuilder();
		$qb->select('c')
		->from('Entities\Financeiro\Categoria', 'c');

		$where	= $qb->expr()->andX();
		$where->add($qb->expr()->eq(1,1));
		foreach ($params as $key => $value)
		{
			$where->add($qb->expr()->eq($key, $value));

		}
		$qb->where($where)
		->orderBy('c.nrcodigo');

		return $this->getEntityManager()->createQuery($qb->getDQL());
	}

	public function listCombo($tpnatureza)
	{
		$criteria	= array(
				'c.flstatus'	=> 1,
				'c.tpnatureza'	=> "'{$tpnatureza}'"
			);
		$return	= array();
		foreach ($this->listar($criteria)->getResult() as $value)
		{
			$return[$value->get('idcategoria')]	= $value->get('nrcodigo').' - '.$value->get('dsnome');
		}
		return $return;
	}

	public function proximoCodigo(\Entities\Financeiro\Categoria $categoriapai)
	{
		$dql	= "SELECT MAX(c.nrcodigo) nrcodigo
				FROM Entities\Financeiro\Categoria c
				WHERE c.categoriapai = {$categoriapai->getId()}";
		$query	= $this->getEntityManager()->createQuery($dql);

		$result	= $query->getResult(Query::HYDRATE_OBJECT);

		if (count($result))
			return $result[0]['nrcodigo'];
		else
			return 0;
	}

	public function proximoCodigoReduzido()
	{
		$dql	= "SELECT MAX(c.nrcodigoreduzido) nrcodigoreduzido
				FROM Entities\Financeiro\Categoria c";
		$query	= $this->getEntityManager()->createQuery($dql);

		$result	= $query->getResult(Query::HYDRATE_OBJECT);

		if (count($result))
			return $result[0]['nrcodigoreduzido'] + 1;
		else
			return 0;
	}
}